package com.example.common.webSocket;

import javax.sound.sampled.*;
import java.net.*;

public class VoiceChat {
    private static final int BUFFER_SIZE = 1024; // 音频缓冲区大小
    private static final int PORT = 50005; // 语音通信端口
    private static final String TARGET_IP = "192.168.1.100"; // 对方设备的IP

    public static void main(String[] args) {
        new Thread(VoiceChat::startReceiving).start(); // 启动接收线程
        new Thread(VoiceChat::startSending).start();   // 启动发送线程
    }

    // 录音并发送语音数据
    private static void startSending() {
        try {
            DatagramSocket socket = new DatagramSocket();
            InetAddress targetAddress = InetAddress.getByName(TARGET_IP);
            AudioFormat format = getAudioFormat();
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(info);
            microphone.open(format);
            microphone.start();

            byte[] buffer = new byte[BUFFER_SIZE];

            while (true) {
                int bytesRead = microphone.read(buffer, 0, buffer.length);
                DatagramPacket packet = new DatagramPacket(buffer, bytesRead, targetAddress, PORT);
                socket.send(packet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 接收语音数据并播放
    private static void startReceiving() {
        try {
            DatagramSocket socket = new DatagramSocket(PORT);
            AudioFormat format = getAudioFormat();
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            SourceDataLine speakers = (SourceDataLine) AudioSystem.getLine(info);
            speakers.open(format);
            speakers.start();

            byte[] buffer = new byte[BUFFER_SIZE];

            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);
                speakers.write(packet.getData(), 0, packet.getLength());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 配置音频格式
    private static AudioFormat getAudioFormat() {
        return new AudioFormat(16000.0f, 16, 1, true, false); // 16kHz, 16位, 单声道, PCM
    }
}
